package com.pivotal.cloud.crypto.keygen;

import java.util.Base64;

/**
 * @className: com.pivotal.cloud.security.crypto.keygen.Base64StringKeyGenerator
 * @projectName: PivotalCloud项目
 * @module: PivotalCloud项目-Base64StringKeyGenerator类，主要位于Security安全模块-Base64模式Key生成器模块
 * @content: Base64StringKeyGenerator-Base64模式Key生成器
 * @author: Powered by Marklin
 * @datetime: 2025-06-24 15:09
 * @version: 1.0.0
 * @copyright: Copyright © 2018-2025 PivotalCloud Systems Incorporated. All rights
 * reserved.
 */
public class Base64StringKeyGenerator implements StringKeyGenerator {

	private static final int DEFAULT_KEY_LENGTH = 32;

	private final BytesKeyGenerator keyGenerator;

	private final Base64.Encoder encoder;

	public Base64StringKeyGenerator() {
		this(32);
	}

	public Base64StringKeyGenerator(int keyLength) {
		this(Base64.getEncoder(), keyLength);
	}

	public Base64StringKeyGenerator(Base64.Encoder encoder) {
		this(encoder, 32);
	}

	public Base64StringKeyGenerator(Base64.Encoder encoder, int keyLength) {
		if (encoder == null) {
			throw new IllegalArgumentException("encode cannot be null");
		}
		else if (keyLength < 32) {
			throw new IllegalArgumentException("keyLength must be greater than or equal to32");
		}
		else {
			this.encoder = encoder;
			this.keyGenerator = KeyGenerators.secureRandom(keyLength);
		}
	}

	/**
	 * 生成Key
	 * @return 返回值
	 */
	@Override
	public String generateKey() {
		byte[] key = this.keyGenerator.generateKey();
		byte[] base64EncodedKey = this.encoder.encode(key);
		return new String(base64EncodedKey);
	}

}
